package com.homedo.odin.solution.service.bizservice.mng;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.CommonDataUtil;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.odin.solution.contract.pc.SpecificationAddPcReq;
import com.homedo.odin.solution.contract.pc.SpecificationDetailPcResp;
import com.homedo.odin.solution.contract.pc.SpecificationEditPcReq;
import com.homedo.odin.solution.contract.pc.SpecificationListResp;
import com.homedo.odin.solution.contract.pc.StandardIndexReq;
import com.homedo.odin.solution.contract.pc.USpecificationDetailResp;
import com.homedo.odin.solution.enumcode.basic.BusinessTypeEnum;
import com.homedo.odin.solution.enumcode.basic.CommonTypeDataEnum;
import com.homedo.odin.solution.enumcode.basic.DownloadCollectEnum;
import com.homedo.odin.solution.enumcode.basic.ErrorCodeEnum;
import com.homedo.odin.solution.enumcode.basic.FromTypeEnum;
import com.homedo.odin.solution.enumcode.other.MemberLevelEnum;
import com.homedo.odin.solution.enumcode.specification.OrderBusinessTypeEnum;
import com.homedo.odin.solution.enumcode.specification.SpecificationStatus;
import com.homedo.odin.solution.enumcode.user.PayStateEnum;
import com.homedo.odin.solution.model.dto.AttachmentInfoResponseBean;
import com.homedo.odin.solution.model.dto.PageBean;
import com.homedo.odin.solution.model.dto.SpecificationListResponseBean;
import com.homedo.odin.solution.model.entity.Attachment;
import com.homedo.odin.solution.model.entity.CommonTypeData;
import com.homedo.odin.solution.model.entity.Specification;
import com.homedo.odin.solution.model.entity.UserPayOrder;
import com.homedo.odin.solution.model.entity.UserSpecification;
import com.homedo.odin.solution.service.AttachmentServiceImpl;
import com.homedo.odin.solution.service.CommonTypeDataServiceImpl;
import com.homedo.odin.solution.service.SpecificationServiceImpl;
import com.homedo.odin.solution.service.UserPayOrderServiceImpl;
import com.homedo.odin.solution.service.UserSpecificationServiceImpl;
import com.homedo.odin.solution.service.common.HomedoService;
import com.homedo.odin.solution.util.SpecificationConvertUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: zhaoxudong
 * @date: 2018/4/10 17:23
 * @Description:
 */
@Service
public class StandardsBizService {

    @Autowired
    SpecificationServiceImpl specificationService;
    @Autowired
    AttachmentServiceImpl attachmentService;
    @Autowired
    CommonTypeDataServiceImpl commonTypeDataService;
    @Autowired
    HomedoService homedoService;
    @Autowired
    UserSpecificationServiceImpl userSpecificationService;
    @Autowired
    UserPayOrderServiceImpl userPayOrderService;

    public SpecificationListResp list(Integer userId, Integer firstClassify, Integer secondClassify, String zone,
            Integer createTimeSort, Integer isMy, String keyword, Integer pageNum, Integer pageSize) {
        List<SpecificationListResponseBean> responseList = new ArrayList<SpecificationListResponseBean>();
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Specification> queryResult = null;
        if (isMy != null && 1 == isMy.intValue()) {
            queryResult = new PageInfo<>(specificationService
                    .queryMySpecificationListForPc(userId, firstClassify, secondClassify, zone, createTimeSort));
        } else {
            queryResult = new PageInfo<>(specificationService
                    .querySpecificationListForPc(userId, firstClassify, secondClassify, zone, createTimeSort, keyword));
        }

        List<Specification> queryList = queryResult.getList();
        if (CollectionUtils.isNotEmpty(queryList)) {
            SpecificationListResponseBean specificationResponse;
            for (Specification specification : queryList) {
                specificationResponse = new SpecificationListResponseBean();
                SpecificationConvertUtils.convert(specification, specificationResponse);
                if (userId != null) {
                    specificationResponse.setIsMy((specification.getUserId().intValue() == userId.intValue() ? 1 : 0));
                } else {
                    specificationResponse.setIsMy(0);
                }
                //增加附件转图片字段
                List<AttachmentInfoResponseBean> attachmentInfoList = new ArrayList<AttachmentInfoResponseBean>();
                List<Attachment> list = attachmentService
                        .queryAttachmentByBusinessId(specification.getSpecificationId(),
                                BusinessTypeEnum.SPECIFICATION.getDbValue());
                for (Attachment attachment : list) {
                    AttachmentInfoResponseBean attachmentInfo = new AttachmentInfoResponseBean();
                    attachmentInfo.setId(attachment.getId());
                    attachmentInfo.setBusinessId(attachment.getBusinessId());
                    attachmentInfo.setBusinessType(attachment.getBusinessType());
                    attachmentInfo.setAttachmentUrl(attachment.getAttachmentUrl());
                    attachmentInfo.setAttachmentPicture(attachment.getAttachmentPicture());
                    attachmentInfo.setCreateTime(attachment.getCreateTime());
                    attachmentInfoList.add(attachmentInfo);
                }
                specificationResponse.setAttachmentInfoList(attachmentInfoList);
                //
                responseList.add(specificationResponse);
            }

        }
        SpecificationListResp resp = BeanUtils.transfrom(SpecificationListResp.class, queryResult);
        resp.setList(responseList);
        return resp;
    }

    public void add(SpecificationAddPcReq specificationAddBean) {
        if (!SpecificationConvertUtils.validate(specificationAddBean)) {
            throw new BizException(Meta.CODE_451.getCode(), "输入参数有误！");
        }
        Integer firstClassify = specificationAddBean.getFirstClassify();//一级分类
        HashMap<String, String> hyghflMap = commonTypeDataService.getDataById(CommonTypeDataEnum.HYGFFL.getDbValue());
        if (!CommonDataUtil.validate(String.valueOf(firstClassify), hyghflMap)) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "行业规范一级分类不合法!");
        }
        Integer secondClassify = specificationAddBean.getSecondClassify();//二级分类
        if (!CommonDataUtil.validate(String.valueOf(secondClassify), hyghflMap)) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "行业规范二级分类不合法!");
        }
        Specification specification = new Specification();
        SpecificationConvertUtils.convert(specification, specificationAddBean);
        specification.setFormType(FromTypeEnum.FRONT_UPLOAD.getDbValue());
        specification.setStatus(SpecificationStatus.AUDITING.getDbValue());
        Long specificationId = specificationService.addSpecification(specification);
        //增加附件信息
        String attachment = specification.getAttachment();
        attachmentService.addAttachment(attachment, specificationId, BusinessTypeEnum.SPECIFICATION.getDbValue());
    }

    public USpecificationDetailResp basic(Integer userId, Long specificationId) {
        if (!NumberHelper.validatePositive(specificationId) ||
                !NumberHelper.validatePositive(userId)) {
            throw new BizException(Meta.CODE_451.getCode(), "参数有误！");
        }
        Specification specification = specificationService.getSpecification(specificationId);
        if (specification == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该行业规范不存在!");
        }
        if (specification.getUserId().intValue() != userId.intValue()) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "当前用户不是该规范上传用户");
        }
        USpecificationDetailResp specificationDetailBean = BeanUtils
                .transfrom(USpecificationDetailResp.class, specification);
        return specificationDetailBean;
    }

    public SpecificationDetailPcResp detail(Long specificationId, Integer userId, Integer memberLevel) {
        if (!NumberHelper.validatePositive(specificationId)) {
            throw new BizException(Meta.CODE_451.getCode(), "参数不正确");
        }
        Specification specification = specificationService.getSpecification(specificationId);
        if (specification == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该行业规范不存在!");
        }
        if (!NumberHelper.validatePositive(userId)) {
            if (SpecificationStatus.UNSHELVE.getDbValue().equals(specification.getStatus())) {
                throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "该行业规范已下架!");
            }
        } else if (!specification.getUserId().equals(userId)) {
            if (SpecificationStatus.UNSHELVE.getDbValue().equals(specification.getStatus())) {
                throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "该行业规范已下架!");
            }
        }
        SpecificationDetailPcResp specificationDetail = BeanUtils
                .transfrom(SpecificationDetailPcResp.class, specification);
        specificationDetail.setIsCollect(0);
        specificationDetail.setIsMy(0);
        specificationDetail.setUserIsDownload(false);
        //二级分类名称
        CommonTypeData commonTypeData = commonTypeDataService.getCommonTypeDataById(specification.getSecondClassify());
        if (commonTypeData != null) {
            specificationDetail.setSecondClassifyStr(commonTypeData.getName());
        }
        if (NumberHelper.validatePositive(userId)) {
            UserSpecification userSpecification = userSpecificationService
                    .getUserSpecification(userId, specification.getSpecificationId(),
                            DownloadCollectEnum.COLLECTION.getDbValue());
            //是否收藏 0:未收藏 1:已收藏
            specificationDetail
                    .setIsCollect((userSpecification == null || userSpecification.getCollectionStatus() == 1) ? 0 : 1);
            //是否是我的方案
            specificationDetail.setIsMy(specification.getUserId().intValue() == userId.intValue() ? 1 : 0);
            //我的方案可以下载
            specificationDetail
                    .setUserIsDownload(specification.getUserId().intValue() == userId.intValue() ? true : false);
            //判断当前用户是否可以下载
            if (specification.getCharges().compareTo(BigDecimal.ZERO) <= 0) {
                //查询当前用户当天免费规范下载次数
                Integer downloadCount = userSpecificationService
                        .queryFreeSpecificationDownloadCount(userId, DownloadCollectEnum.DOWNLOAD.getDbValue());
                if (NumberHelper.validatePositive(memberLevel)) {
                    if (MemberLevelEnum.VIP_LEVEL_1.getDbValue().equals(memberLevel) || MemberLevelEnum.VIP_LEVEL_2
                            .getDbValue().equals(memberLevel)) {
                        if (10 > downloadCount.intValue()) {
                            specificationDetail.setUserIsDownload(true);
                        }
                    } else if (MemberLevelEnum.VIP_LEVEL_3.getDbValue().equals(memberLevel)
                            || MemberLevelEnum.VIP_LEVEL_4.getDbValue().equals(memberLevel)) {
                        if (15 > downloadCount.intValue()) {
                            specificationDetail.setUserIsDownload(true);
                        }
                    } else if (MemberLevelEnum.VIP_LEVEL_5.getDbValue().equals(memberLevel)
                            || MemberLevelEnum.VIP_LEVEL_6.getDbValue().equals(memberLevel)) {
                        if (20 > downloadCount.intValue()) {
                            specificationDetail.setUserIsDownload(true);
                        }
                    }
                } else {
                    //非会员只能免费下载三次
                    if (3 > downloadCount.intValue()) {
                        specificationDetail.setUserIsDownload(true);
                    }
                }
            } else {
                //付费规范
                //判断是否已经完成支付
                UserPayOrder userPayOrder = userPayOrderService.queryUserPayOrder(specificationId, userId);
                if (userPayOrder != null) {
                    specificationDetail.setOrderNo(userPayOrder.getOrderNo());
                    specificationDetail.setPayStatus(userPayOrder.getStatus());
                }
                if (userPayOrder != null && userPayOrder.getStatus().intValue() == PayStateEnum.PAYCOMPLETE
                        .getDbValue()) {
                    //完成付款
                    specificationDetail.setUserIsDownload(true);
                }
            }

        }
        //获取推荐行业规范列表
        List<SpecificationListResponseBean> recommendList = new ArrayList<SpecificationListResponseBean>();
        List<Specification> list = specificationService
                .queryRecommendSpecificationList(specificationId, specification.getSecondClassify());
        if (CollectionUtils.isNotEmpty(list)) {
            for (Specification detail : list) {
                SpecificationListResponseBean specificationList = new SpecificationListResponseBean();
                specificationList.setSpecificationId(detail.getSpecificationId());
                specificationList.setSpecificationIdStr(detail.getSpecificationId().toString());
                specificationList.setSpecificationName(detail.getSpecificationName());
                specificationList.setMatchPic(detail.getMatchPic());
                specificationList.setAttachment(detail.getAttachment());
                recommendList.add(specificationList);
            }
            if (list.size() < 10) {
                List<Specification> tenList = specificationService
                        .queryTheFirstTenSpecification(specificationId, specification.getSecondClassify(),
                                10 - list.size());
                if (CollectionUtils.isNotEmpty(tenList)) {
                    for (Specification specification2 : tenList) {
                        SpecificationListResponseBean specificationList = new SpecificationListResponseBean();
                        specificationList.setSpecificationId(specification2.getSpecificationId());
                        specificationList.setSpecificationIdStr(specification2.getSpecificationId().toString());
                        specificationList.setSpecificationName(specification2.getSpecificationName());
                        specificationList.setMatchPic(specification2.getMatchPic());
                        specificationList.setAttachment(specification2.getAttachment());
                        recommendList.add(specificationList);
                    }
                }
            }
        } else {
            List<Specification> tenList = specificationService
                    .queryTheFirstTenSpecification(specificationId, specification.getSecondClassify(), 10);
            for (Specification detail : tenList) {
                SpecificationListResponseBean specificationList = new SpecificationListResponseBean();
                specificationList.setSpecificationId(detail.getSpecificationId());
                specificationList.setSpecificationIdStr(detail.getSpecificationId().toString());
                specificationList.setSpecificationName(detail.getSpecificationName());
                specificationList.setMatchPic(detail.getMatchPic());
                specificationList.setAttachment(detail.getAttachment());
                recommendList.add(specificationList);
            }
        }
        specificationDetail.setRecommendList(recommendList);

        //增加附件转图片字段
        List<AttachmentInfoResponseBean> attachmentInfoList = new ArrayList<AttachmentInfoResponseBean>();
        List<Attachment> attachmentList = attachmentService
                .queryAttachmentByBusinessId(specification.getSpecificationId(),
                        BusinessTypeEnum.SPECIFICATION.getDbValue());
        AttachmentInfoResponseBean attachmentInfo;
        for (Attachment attachment : attachmentList) {
            attachmentInfo = new AttachmentInfoResponseBean();
            attachmentInfo.setId(attachment.getId());
            attachmentInfo.setBusinessId(attachment.getBusinessId());
            attachmentInfo.setBusinessType(attachment.getBusinessType());
            attachmentInfo.setAttachmentUrl(attachment.getAttachmentUrl());
            attachmentInfo.setAttachmentPicture(attachment.getAttachmentPicture());
            attachmentInfo.setCreateTime(attachment.getCreateTime());
            attachmentInfoList.add(attachmentInfo);
        }
        specificationDetail.setAttachmentInfoList(attachmentInfoList);
        //
        //浏览量+1
        specificationService.addSpecificationPageView(specificationId);
        return specificationDetail;
    }

    public void edit(SpecificationEditPcReq specificationEditBean) {
        Specification specification = specificationService
                .getSpecification(Long.parseLong(specificationEditBean.getSpecificationId
                        ()));
        if (specification == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该行业规范不存在!");
        }
        if (specificationEditBean.getUserId().intValue() != specification.getUserId().intValue()) {
            throw new BizException(Meta.CODE_451.getCode(), "当前编辑用户不是该规范的上传用户");
        }
        //状态不为审核驳回状态 不允许编辑
        if (specification.getStatus().intValue() != SpecificationStatus.AUDITFAIL.getDbValue()) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "该行业规范不是审核驳回状态，无法修改！");
        }

        Integer firstClassify = specificationEditBean.getFirstClassify();//一级分类
        HashMap<String, String> hyghflMap = commonTypeDataService.getDataById(CommonTypeDataEnum.HYGFFL.getDbValue());
        if (!CommonDataUtil.validate(String.valueOf(firstClassify), hyghflMap)) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "行业规范一级分类不合法!");
        }
        Integer secondClassify = specificationEditBean.getSecondClassify();//二级分类
        if (!CommonDataUtil.validate(String.valueOf(secondClassify), hyghflMap)) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "行业规范二级分类不合法!");
        }
        SpecificationConvertUtils.convert(specification, specificationEditBean);
        specification.setStatus(SpecificationStatus.AUDITING.getDbValue());
        specificationService.updateSpecification(specification);
        //先删除原有方案附件
        attachmentService.delAttachmentByBusinessId(specification.getSpecificationId(),
                BusinessTypeEnum.SPECIFICATION.getDbValue());
        //增加方案附件详细信息
        String attachment = specification.getAttachment();
        attachmentService.addAttachment(attachment, specification.getSpecificationId(),
                BusinessTypeEnum.SPECIFICATION.getDbValue());
    }

    /****************************liStsar*/
    /**
     * 获取首页查询规范信息列表
     * @param standardIndexReq
     */
    public SpecificationListResp queryIndexSolution(StandardIndexReq standardIndexReq) {
        PageBean pageBean = new PageBean(standardIndexReq.getPageNum(), standardIndexReq.getPageSize());
        List<SpecificationListResponseBean> responseList = new ArrayList<SpecificationListResponseBean>();
        PageInfo<Specification> pageInfo = specificationService.querySpecificationListFormSelect(standardIndexReq.getKeyword(),standardIndexReq.getUserId(),pageBean);
        List<Specification> queryList = pageInfo.getList();
        for (Specification specification : queryList) {
            SpecificationListResponseBean specificationResponse = new SpecificationListResponseBean();
            SpecificationConvertUtils.convert(specification, specificationResponse);
            if(standardIndexReq.getUserId() != null){
                specificationResponse.setIsMy((specification.getUserId().intValue() == standardIndexReq.getUserId().intValue() ? 1 : 0));
            }else{
                specificationResponse.setIsMy(0);
            }
            //增加附件转图片字段
            List<AttachmentInfoResponseBean> attachmentInfoList = new ArrayList<AttachmentInfoResponseBean>();
            List<Attachment> list = attachmentService.queryAttachmentByBusinessId(specification.getSpecificationId(),
                OrderBusinessTypeEnum.SPECIFICATION.getDbValue());
            for (Attachment attachment : list) {
                AttachmentInfoResponseBean attachmentInfo = new AttachmentInfoResponseBean();
                attachmentInfo.setId(attachment.getId());
                attachmentInfo.setBusinessId(attachment.getBusinessId());
                attachmentInfo.setBusinessType(attachment.getBusinessType());
                attachmentInfo.setAttachmentUrl(attachment.getAttachmentUrl());
                attachmentInfo.setAttachmentPicture(attachment.getAttachmentPicture());
                attachmentInfo.setCreateTime(attachment.getCreateTime());
                attachmentInfoList.add(attachmentInfo);
            }
            specificationResponse.setAttachmentInfoList(attachmentInfoList);
            //
            responseList.add(specificationResponse);
        }

        SpecificationListResp resp = BeanUtils.transfrom(SpecificationListResp.class, pageInfo);
        resp.setList(responseList);
        return resp;
    }

    /****************************liend*/
}
